package com.supreme.cacheserver.controller;

import com.supreme.commonboot.utils.AjaxResp;
import com.supreme.commonboot.utils.SupremeAwareUtils;
import com.supreme.commonentity.mysql.primary.MBTest;
import com.supreme.commonredis.config.redistype.RedisSerializableType;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping(value = "redis-string")
public class RedisStringController {

    @Resource
    private RedisTemplate<String, Serializable> redisTemplate;

    @Resource(name = "sstRedisTemplate")
    private RedisSerializableType sstRedisTemplate;

    @Resource
    private List<RedisTemplate<String, Serializable>> redisTemplateList;

    @GetMapping(value = "redisTemplateInfo")
    public AjaxResp redisTemplateInfo() {
        System.out.println("redisTemplate: " + redisTemplate);
        System.out.println("sstRedisTemplate: " + sstRedisTemplate);
        return AjaxResp.instance();
    }

    @GetMapping(value = "beanFactoryGetStr/{key}")
    public AjaxResp beanFactoryGetString(@PathVariable(value = "key") String key) {
        final RedisSerializableType redisTemplate = SupremeAwareUtils.getBeanFactory(RedisSerializableType.class);
        final Object result = redisTemplate.opsForValue().get(key);
        return AjaxResp.instance(result);
    }

    @GetMapping(value = "getAllKeys")
    public AjaxResp getAllKeys() {
        final Set<String> keys = redisTemplate.keys("*");
        return AjaxResp.instance(keys);
    }

    @GetMapping(value = "getAllKeys/{index}")
    public AjaxResp getAllKeys(@PathVariable(value = "index") Integer index) {
        RedisTemplate<String, Serializable> redisTemplateIdx = redisTemplateList.get(index);
        Set<String> keys = redisTemplateIdx.keys("*");
        return AjaxResp.instance(keys);
    }

    @GetMapping(value = "set/{key}/{val}")
    public AjaxResp setStr(@PathVariable(value = "key") String key, @PathVariable(value = "val") String val) {
        redisTemplate.opsForValue().set(key, val);
        return AjaxResp.instance();
    }

    @GetMapping(value = "get/{key}")
    public AjaxResp getStr(@PathVariable(value = "key") String key) {
        String value = (String) redisTemplate.opsForValue().get(key);
        return AjaxResp.instance(value);
    }

    @PostMapping(value = "setTest/{key}")
    public AjaxResp setTest(@PathVariable(value = "key") String key, @RequestBody MBTest test) {
        redisTemplate.opsForValue().set(key, test);
        return AjaxResp.instance();
    }

    @PostMapping(value = "getTest/{key}")
    public AjaxResp setTest(@PathVariable(value = "key") String key) {
        MBTest test = (MBTest) redisTemplate.opsForValue().get(key);
        return AjaxResp.instance(test);
    }
}
